﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Publicuse.Appication;
using Publicuse.Application.system;
using Publicuse.Autofac;
using Publicuse.Entity;
using Publicuse.Util;
using static FreeSql.Internal.GlobalFilter;

namespace Publicuse.Application
{
    public class StatisticsApplication
    {
        private static BaesApplication baseApplication;
        private static StatisticsApplication userApplication;

        public static StatisticsApplication GetApplication(ServiceContainer container)
        {
            baseApplication = new BaesApplication(container);
            return userApplication;
        }

        static StatisticsApplication()
        {
            userApplication = new StatisticsApplication();
        }

        /// <summary>
        /// 操作柱形访问量（统计新增、删除、修改、导入操作记录数）
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult> GetOperate()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var table = TableAtributeUtil.GetTable<Log>();
                var LoginCode = HttpContextExtendBase.GetLoginCode();
                var LoginAppid = HttpContextExtendBase.GetLoginAppid();
                var tableb = TableAtributeUtil.GetTable<Spconf>();
                var sql = $"select sValue from {tableb} where sCode sCode='operate' and status=1;";
                var slist = baseApplication.mySqlSugar.Query<Spconf>(sql, null, out var msg);
                var addday = 0;
                if (string.IsNullOrEmpty(msg) && slist != null && slist.Count > 0)
                {
                    addday = slist.FirstOrDefault().sValue.GetIntValue();
                }
                var startTime = DateTime.Now.AddDays(addday).ToString("yyyy-MM-dd 00:00:00");
                var endTime = DateTime.Now.AddDays(addday).ToString("yyyy-MM-dd 23:59:59");
                if (
                    string.Compare(LoginCode, "ajng", true) == 0
                    || string.Compare(LoginAppid, "admin", true) == 0
                )
                {
                    sql =
                        $"select * from {table} where cTime between '{startTime}' and '{endTime}'  and FIND_IN_SET(ltype,'新增,删除,修改,导入');";
                }
                else
                {
                    sql =
                        $"select * from {table} where cTime between '{startTime}' and '{endTime}' and luser='{LoginCode}' and FIND_IN_SET(ltype,'新增,删除,修改,导入');";
                }
                var list = baseApplication.mySqlSugar.Query<Log>(sql, null, out msg);
                Operate operate = new Operate();
                if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
                {
                    var addCount = list.Where(x => x.ltype == "新增").Count();
                    var delCount = list.Where(x => x.ltype == "删除").Count();
                    var updateCount = list.Where(x => x.ltype == "修改").Count();
                    var importCount = list.Where(x => x.ltype == "导入").Count();
                    operate.addCount = addCount;
                    operate.delCount = delCount;
                    operate.updateCount = updateCount;
                    operate.importCount = importCount;

                    operate.xaxis.AddRange(new string[] { "新增", "删除", "修改", "导入" });
                    operate.series.AddRange(
                        new double[] { addCount, delCount, updateCount, importCount }
                    );
                }
                result.data = operate;
                return result;
            });
        }

        /// <summary>
        /// 模块综合访问量(模块对应的新增、删除、修改、导入)
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult> GetWebsitetraffic()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var table = TableAtributeUtil.GetTable<Log>();
                var LoginCode = HttpContextExtendBase.GetLoginCode();
                var LoginAppid = HttpContextExtendBase.GetLoginAppid();
                var tableb = TableAtributeUtil.GetTable<Spconf>();
                var sql =
                    $"select sValue from {tableb} where sCode sCode='websitetraffic' and status=1;";
                var slist = baseApplication.mySqlSugar.Query<Spconf>(sql, null, out var msg);
                var addday = 0;
                if (string.IsNullOrEmpty(msg) && slist != null && slist.Count > 0)
                {
                    addday = slist.FirstOrDefault().sValue.GetIntValue();
                }
                var startTime = DateTime.Now.AddDays(addday).ToString("yyyy-MM-dd 00:00:00");
                var endTime = DateTime.Now.AddDays(addday).ToString("yyyy-MM-dd 23:59:59");
                if (
                    string.Compare(LoginCode, "ajng", true) == 0
                    || string.Compare(LoginAppid, "admin", true) == 0
                )
                {
                    sql =
                        $"select * from {table} where cTime between '{startTime}' and '{endTime}' and FIND_IN_SET(ltype,'新增,删除,修改,导入');";
                }
                else
                {
                    sql =
                        $"select * from {table} where cTime between '{startTime}' and '{endTime}' and luser='{LoginCode}' and FIND_IN_SET(ltype,'新增,删除,修改,导入');";
                }
                var list = baseApplication.mySqlSugar.Query<Log>(sql, null, out msg);
                Websitetraffic websitetraffic = new Websitetraffic();
                if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
                {
                    websitetraffic.labels = list.Select(x => x.lmodule).Distinct().ToList();
                    var namelist = new List<string>() { "新增", "删除", "修改", "导入" };
                    List<string> typelist = new List<string>() { "column", "area", "line" };
                    Random random = new Random();
                    var index = 0;
                    foreach (var item in namelist)
                    {
                        var type = string.Empty;
                        if (index >= typelist.Count)
                        {
                            int randomNumber = random.Next(1, 3);
                            type = typelist[randomNumber];
                        }
                        else
                        {
                            type = typelist[index];
                        }
                        seriesModel seriesModel = new seriesModel() { name = item, type = type };
                        List<double> doubles = new List<double>();
                        websitetraffic.labels.ForEach(itemb =>
                        {
                            var data = list.Count(o => o.ltype == item && o.lmodule == itemb);
                            doubles.Add(data);
                        });
                        seriesModel.data = doubles;
                        websitetraffic.series.Add(seriesModel);
                        index++;
                    }
                }
                result.data = websitetraffic;
                return result;
            });
        }

        /// <summary>
        /// 模块扇形访问量
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult> GetCurrenttraffic()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var table = TableAtributeUtil.GetTable<Log>();
                var LoginCode = HttpContextExtendBase.GetLoginCode();
                var LoginAppid = HttpContextExtendBase.GetLoginAppid();
                var tableb = TableAtributeUtil.GetTable<Spconf>();
                var sql =
                    $"select sValue from {tableb} where sCode sCode='websitetraffic' and status=1;";
                var slist = baseApplication.mySqlSugar.Query<Spconf>(sql, null, out var msg);
                var addday = 0;
                if (string.IsNullOrEmpty(msg) && slist != null && slist.Count > 0)
                {
                    addday = slist.FirstOrDefault().sValue.GetIntValue();
                }
                var startTime = DateTime.Now.AddDays(addday).ToString("yyyy-MM-dd 00:00:00");
                var endTime = DateTime.Now.AddDays(addday).ToString("yyyy-MM-dd 23:59:59");
                if (
                    string.Compare(LoginCode, "ajng", true) == 0
                    || string.Compare(LoginAppid, "admin", true) == 0
                )
                {
                    sql =
                        $"select * from {table} where cTime between '{startTime}' and '{endTime}' and FIND_IN_SET(ltype,'新增,删除,修改,导入');";
                }
                else
                {
                    sql =
                        $"select * from {table} where cTime between '{startTime}' and '{endTime}' and luser='{LoginCode}' and FIND_IN_SET(ltype,'新增,删除,修改,导入');";
                }
                var list = baseApplication.mySqlSugar.Query<Log>(sql, null, out msg);
                Currenttraffic currenttraffic = new Currenttraffic();
                if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
                {
                    currenttraffic.labels = list.Select(x => x.lmodule).Distinct().ToList();
                    var modulelist = list.GroupBy(o => o.lmodule);
                    foreach (var item in modulelist)
                    {
                        currenttraffic.series.Add(item.Count());
                    }
                }
                result.data = currenttraffic;
                return result;
            });
        }

        /// <summary>
        /// 模块雷达访问量
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult> GetRadartraffic()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var table = TableAtributeUtil.GetTable<Log>();
                var LoginCode = HttpContextExtendBase.GetLoginCode();
                var LoginAppid = HttpContextExtendBase.GetLoginAppid();
                var tableb = TableAtributeUtil.GetTable<Spconf>();
                var sql =
                    $"select sValue from {tableb} where sCode sCode='websitetraffic' and status=1;";
                var slist = baseApplication.mySqlSugar.Query<Spconf>(sql, null, out var msg);
                var addday = 0;
                if (string.IsNullOrEmpty(msg) && slist != null && slist.Count > 0)
                {
                    addday = slist.FirstOrDefault().sValue.GetIntValue();
                }
                var startTime = DateTime.Now.AddDays(addday).ToString("yyyy-MM-dd 00:00:00");
                var endTime = DateTime.Now.AddDays(addday).ToString("yyyy-MM-dd 23:59:59");
                if (
                    string.Compare(LoginCode, "ajng", true) == 0
                    || string.Compare(LoginAppid, "admin", true) == 0
                )
                {
                    sql =
                        $"select * from {table} where cTime between '{startTime}' and '{endTime}' and FIND_IN_SET(ltype,'新增,删除,修改,导入');";
                }
                else
                {
                    sql =
                        $"select * from {table} where cTime between '{startTime}' and '{endTime}' and luser='{LoginCode}' and FIND_IN_SET(ltype,'新增,删除,修改,导入');";
                }
                var list = baseApplication.mySqlSugar.Query<Log>(sql, null, out msg);
                Radartraffic radartraffic = new Radartraffic();
                if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
                {
                    radartraffic.categories = list.Select(x => x.lmodule).Distinct().ToList();
                    var namelist = new List<string>() { "新增", "删除", "修改", "导入" };
                    foreach (var item in namelist)
                    {
                        seriesModel seriesModel = new seriesModel() { name = item };
                        List<double> doubles = new List<double>();
                        radartraffic.categories.ForEach(itemb =>
                        {
                            var data = list.Count(o => o.ltype == item && o.lmodule == itemb);
                            doubles.Add(data);
                        });
                        seriesModel.data = doubles;
                        radartraffic.series.Add(seriesModel);
                    }
                }
                result.data = radartraffic;
                return result;
            });
        }

        /// <summary>
        /// 登录时间表
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult> GetLoginSchedule()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var table = TableAtributeUtil.GetTable<SigninInfo>();
                var LoginCode = HttpContextExtendBase.GetLoginCode();
                var LoginAppid = HttpContextExtendBase.GetLoginAppid();
                var tableb = TableAtributeUtil.GetTable<Spconf>();
                var sql =
                    $"select sValue from {tableb} where sCode sCode='websitetraffic' and status=1;";
                var slist = baseApplication.mySqlSugar.Query<Spconf>(sql, null, out var msg);
                var addday = 0;
                if (string.IsNullOrEmpty(msg) && slist != null && slist.Count > 0)
                {
                    addday = slist.FirstOrDefault().sValue.GetIntValue();
                }
                var startTime = DateTime.Now.AddDays(addday).ToString("yyyy-MM-dd 00:00:00");
                var endTime = DateTime.Now.AddDays(addday).ToString("yyyy-MM-dd 23:59:59");
                if (
                    string.Compare(LoginCode, "ajng", true) == 0
                    || string.Compare(LoginAppid, "admin", true) == 0
                )
                {
                    sql =
                        $"select * from {table} where cTime between '{startTime}' and '{endTime}';";
                }
                else
                {
                    sql =
                        $"select * from {table} where cTime between '{startTime}' and '{endTime}' and logincode='{LoginCode}';";
                }
                var list = baseApplication.mySqlSugar.Query<SigninInfo>(sql, null, out msg);
                List<LoginSchedule> loginSchedules = new List<LoginSchedule>();
                if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
                {
                    list.ForEach(item =>
                    {
                        LoginSchedule loginSchedule = new LoginSchedule()
                        {
                            uCode = item.logincode,
                            loginTime = item.cTime.ToString("yyyy-MM-dd HH:mm:ss"),
                            ipaddress=item.ipaddress
                        };
                        loginSchedules.Add(loginSchedule);
                    });
                }
                result.data = loginSchedules;
                return result;
            });
        }
    }
}
